/*
 * 请求相关,异步api同步封装
 */
import { useUserStore } from '@/store/user.js';
const request = {};

/**
 * http请求
 * @param {Object} opts
 * @param {String} opts.methods 请求方法 GET/POST
 * @param {String} opts.url 请求路径
 * @param {Object} opts.data 请求参数
 * @param {String} opts.contentType 以什么格式类型发送参数 application/json / application/x-www-form-urlencoded
 */
request.globalRequest = (opts) => {
	opts.contentType = opts.contentType || "application/x-www-form-urlencoded"

	return new Promise((resolve, reject) => {
		uni.request({
			url: opts.url,
			method: opts.methods,
			data: opts.data,
			dataType: 'json',
			timeout: 30000,
			header: {
				"Content-Type": opts.contentType,
				'token': uni.getStorageSync('token')
			},
			success: (res) => {
				if (res.data.code == 1002) {
					uni.showToast({
						icon: 'error',
						mask: true,
						title: '登录已失效',
						duration: 2000,
						success() {
							useUserStore().CLEAR_TOKEN();
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/index/index'
								})
							}, 500)
						}
					})
				} else if (res.data.code == 1009) {
					reject(res);
					uni.showToast({
						icon: 'none',
						mask: true,
						title: res.data.msg,
						duration: 2000,
					});
				} else if (res.data.code == 0) {
					resolve(res);
				} else {
					reject(res);
					uni.showToast({
						icon: 'none',
						mask: true,
						title: res.data.msg,
						duration: 2000,
					});
				}

			},
			fail: (err) => {
				uni.showModal({
					content: '请求失败，请稍后再试',
					showCancel: false,
					confirmText: '关闭',
				});
				reject(err)
			}
		})
	})
}


/**
 * http请求
 * @param {Object} opts
 * @param {String} opts.url 请求路径
 * @param {String} opts.filePath 文件路径
 * @param {String} opts.name 文件对应的 key
 * @param {Object} opts.data 请求参数
 */
request.uploadFile = (opts) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: opts.url,
			filePath: opts.filePath,
			name: opts.name,
			header: {
				"Content-Type": "multipart/form-data",
				'token': uni.getStorageSync('token')
			},
			formData: opts.data,
			success: (res) => {
				try {
					if (typeof res.data === 'string') {
						res.data = JSON.parse(res.data);
					}
				} catch (err) {
					console.log(err)
				}
				resolve(res);
			},
			fail: (err) => {
				uni.showModal({
					content: '请求失败，请稍后再试',
					showCancel: false,
					confirmText: '关闭',
				});
				reject(err)
			}
		})
	})
}


export default request